package com.qianfeng.openapi.web.master.controller;

import com.github.pagehelper.PageInfo;
import com.qianfeng.openapi.web.master.bean.AjaxResponse;
import com.qianfeng.openapi.web.master.bean.TableData;
import com.qianfeng.openapi.web.master.pojo.ApiMapping;
import com.qianfeng.openapi.web.master.service.ApiMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author LJF
 * @Date 2020/7/2 16:07
 * @Version 1.0
 */
@RestController
@RequestMapping("/sys/apimapping")
@CrossOrigin(allowCredentials = "true")
public class ApiMappingController {

    @Autowired
    private ApiMappingService apiMappingService;


    @RequestMapping("/table")
    public TableData<ApiMapping> table(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer limit){
        PageInfo<ApiMapping> pageInfo = apiMappingService.getAllApiMappingByPage(page, limit);
        TableData<ApiMapping> tableData = new TableData<>();
        tableData.setCount(pageInfo.getTotal());
        tableData.setData(pageInfo.getList());
        return tableData;
    }

    @RequestMapping("/add")
    public AjaxResponse add(ApiMapping apiMapping){
        try {
            apiMappingService.insertApiMapping(apiMapping);
            return new AjaxResponse(true,"添加成功");
        }catch (Exception ex){
            ex.printStackTrace();
            return new AjaxResponse(false,"添加失败");
        }
    }


    @RequestMapping("/update")
    public AjaxResponse update(ApiMapping apiMapping){
        try {
            apiMappingService.updateApiMapping(apiMapping);
            return new AjaxResponse(true,"更新成功");
        }catch (Exception ex){
            ex.printStackTrace();
            return new AjaxResponse(false,"更新失败");
        }
    }

    @RequestMapping("/delete")
    public AjaxResponse delete(Integer[] ids){
        try {
            apiMappingService.deleteApiMappings(ids);
            return new AjaxResponse(true,"删除成功");
        }catch (Exception ex){
            ex.printStackTrace();
            return new AjaxResponse(false,"删除失败");
        }
    }

    @RequestMapping("/search")
    public TableData<ApiMapping> search(@RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "5") Integer limit,
                                        String gatewayApiName,Integer state){
        PageInfo<ApiMapping> pageInfo = apiMappingService.selectApiMappingByCondition(page, limit, gatewayApiName, state);
        TableData<ApiMapping> tableData = new TableData<>();
        tableData.setCount(pageInfo.getTotal());
        tableData.setData(pageInfo.getList());
        return tableData;

    }


}
